package com.xuzimian.globaldemo.websocket.basicexample;

import org.java_websocket.WebSocketImpl;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @program: global-demo
 * @description:
 * @author: xzm
 * @create: 2019-01-22 11:34
 **/
public class WeSocketDemo {

    /**
     * 开启服务端后可以用http://www.blue-zero.com/WebSocket/ 在线测试websocket工具，输入本机局域网地址进行测试
     *
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public void startWebSocketServer() throws IOException, InterruptedException {
        WebSocketImpl.DEBUG = false;
        int port = 8887; // 端口
        WsServer s = new WsServer(port);
        s.start();
        System.out.println("WsServer started on port: " + s.getPort());
        //控制台挂起线程，监听键盘输入exit结束程序
        BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String in = sysin.readLine();
            s.broadcast(in);
            if (in.equals("exit")) {
                s.stop(1000);
                break;
            }
        }
    }

    @Test
    public void startWebSocketClient() throws IOException {
        String location = "ws://localhost:8887";
        System.out.println("Default server uri not specified: defaulting to \'" + location + "\'");
        new ChatClient(location);
        System.in.read();
    }
}
